<?php

define('stageMode','dev');

class Wall_Fetch{
        

	protected $_url;

	protected $_useragent = 'MOZILLA/4.0 (COMPATIBLE; MSIE 6.0; WINDOWS NT 5.1';

	protected $_content;

	protected $_content_type;

	protected $_content_length;

	protected $_http_code;

	protected $_response;

	protected $_support_curl;

	protected $_info;

	protected $_fetchResult = false;

	public  function __construct($url){
		$this->_support_curl = function_exists('curl_init');
		$this->_url =  $url;
	}

	protected function _curlGet(){
		/*$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $this->_url);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1) ;
		curl_setopt($ch,CURLOPT_HTTPHEADER,array('Expect:'));
		curl_setopt($ch,CURLOPT_TIMEOUT, 300);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch,CURLOPT_USERAGENT,$this->_useragent);

		$this->_response = curl_exec($ch);*/
		$this->_response = Phpfox::getLib('request')->send($this->_url, array(), 'GET', $_SERVER['HTTP_USER_AGENT']);
		$this->_fetchResult = true;
		//print_r($this->_response);die();
		/*if(!curl_errno($ch)){
			$this->_info = curl_getinfo($ch);
			$this->_fetchResult = true;
		}else{
			$this->_result = false;
			if(stageMode == 'dev'){
				echo 'curl error: ', curl_error($ch);
			}
		}
		curl_close($ch);*/
	}

	public function getInfo($name =  NULL){
		if($name == NULL){
			return $this->_info;
		}
		return @$this->_info[$name];
	}

	protected function _fileGet(){
		if($this->_response = @file_get_content($this->_url)){

			$this->_fetchResult = true;
		}
	}

	public function get(){
		if($this->_support_curl){
			$this->_curlGet();
		}else{
			$this->_fileGet();
		}

		return $this->_fetchResult;

	}
	public function getContentType(){
		if($this->_support_curl){
			return @$this->_info['content_type'];
		}
	}

	protected function _getContent(){
		return $this->_response;
	}

	public function getContent(){
		return $this->_response;
	}
}



class Wall_Parse_News{

	protected $_url;

	protected $_host;

	protected $_schema;

	protected $_baseUrl;

	protected $_fetch;

	protected $_content;

	protected $_fetchResult = false;

	public function __construct($url){
		$parts = parse_url($url);
		if($parts && array_key_exists('scheme',$parts) && array_key_exists('host',$parts)){
				
			$this->_schema = $parts['scheme'];
			$this->_host = $parts['host'];
			$this->_baseUrl = sprintf("%s://%s", $this->_schema, $this->_host);
			$this->_url =  $url;
			$this->_fetch =  new Wall_Fetch($url);
			$this->_fetchResult = $this->_fetch->get();
			$this->_content     =   $this->_fetch->getContent();
				
		}else{
			if(stageMode == 'dev'){
				echo br. 'url is not valid';
				print_r($parts);
			}
			$this->_fetchResult = false;
		}
	}

	public function cleanTag($str){
		$str =  str_replace("&gt;","> ", $str);
		$str =  str_replace("&lt;","<", $str);
		$str =  str_replace("&quot;",'"', $str);
		$str =  str_replace("&amp;",'&', $str);
		return strip_tags($str);
	}

	public function getFetch(){
		return $this->_fetch;
	}

	protected function _getTitle(){
		$pattern = '#<title>([^\<]*)</title>#im';
		preg_match ( $pattern, $this->_content, $matches );
		if (is_array ( $matches ) && @$matches [1]) {
			return $matches [1];
		}
		return '';
	}

	protected function _getImagesSrc(){
		$pattern = '#img [^\>]*(thumb|src|thumbnail){1}\s*="(?P<src>[^\"]*)"[^\>]*#im';
		preg_match_all ( $pattern, $this->_content, $matches );
		if (is_array ( $matches ) && ! empty ( $matches ['src'] )) {
			return $matches ['src'];
		}
		return false;
	}

	protected function _getVideoSrc(){
		$pattern = '# src=(?P<src>[^\>]*)#im';
		preg_match ( $pattern, $this->_content, $matches ); // search implicit video.
		return $matches;
	}

	protected function _getVideoThumbs(){
		$pattern = '#\.thumbnailUrl=(?P<src>[^\&]*)#im';
		preg_match_all ( $pattern, $this->_content, $matches ); // search implicit video.
		if (is_array ( $matches ) && is_array ( $matches ['src'] )) {
			$res =  array();
			foreach ( $matches ['src'] as $src ) {
				$res [] = urldecode( $src );
			}
			return $res;
		}
		return false;
			
	}

	protected function _getDesc(){
		$pattern = '#<meta\s+name\s*=\s*"\s*description\s*" content="\s*([^\"]*)\s*"#';
		preg_match ( $pattern, $this->_content, $matches );
		if (is_array ( $matches ) && isset($matches [1])) {
			return $matches [1];
		}
		return '';
	}

	public function getDict(){
		return $this->_dict;
	}

	public function getImages($imgs){
		
    $images = array();
	$baseurl = $this->_baseUrl;
	if($baseurl=="https://www.youtube.com" || $baseurl=="https://youtube.com")
	{
		$baseurl = "http:";
	}
    if(is_array($imgs)){
      foreach ( $imgs as $src ) {
      
        if (strpos ( $src, '?' )) {
        } else if ($src [0] == '/') {
          $images [] = $baseurl . $src;
        } else if (strpos ( $src, "://" )) {
          $images [] = $src;
        }
      }
    }	
		
		return array_unique($images);
	}

	public function getVideo(){
		return $this->_getVideoSrc();
	}

	public function getTitle(){
		return $this->cleanTag($this->_getTitle());
	}

	public function getDesc(){
		return $this->_getDesc();
	}

  protected function isInternal(){
    return 0;
  }

  protected function getCode(){
    return '';
  }

  protected function feedContent(){
    return 1;
  }

	public function getData(){
		$data = array();
		$data['url'] = $this->_url;
		$data['responseCode'] = 'success';
    $data['is_internal'] = '';
    $data['internal_url'] = '';
    $data['base_url'] = '';
    $data['resource_type'] = '';
    $data['rss'] = '';
    $data['title'] = '';
    $data['subtitle'] = '';
    $data['description'] = '';
    $data['code'] = '';

    
    $imgs =  array();
		if(!$this->_fetchResult){
			return $data;
		}

		$contentType = $data['content_type'] = $this->_fetch->getContentType();
		$type = '';

		
		if(strpos($contentType,'image/') !== false){
			$type = 'image';
		}
		if($type == 'image'){
			$data['images'][] = $this->_url;
			$data['images'][] = $this->_url;	
			$data['title']  = $this->_url;
			$data['description'] = $this->_url;
			return $data;
		}

    $data['feed_content'] = 1;
    $data['is_internal'] =  $this->isInternal();
		$data['title']  = $this->getTitle();
		$data['description'] = $this->getDesc();
    $data['code'] =  $this->getCode();
    $data['is_video'] =  0;
		
		$video = $this->_getVideoSrc();
    

    if($video)
		{
			$imgs = $this->_getVideoThumbs();
			
			
      $data['is_video'] =  1;
		}
		if(!$imgs){
			$imgs = $this->_getImagesSrc();
			
		}
		
		$data['images'] = $this->getImages($imgs);
		
		return $data;
	}
}

class Wall_Parse_Youtube extends Wall_Parse_News{

  protected function isInternal(){
   	return 1;
  }

  protected function _getVideoThumbs(){
   
		$pattern = '#data-thumb=\"(?P<src>[^\"]*)#im';
		preg_match_all ( $pattern, $this->_content, $matches ); // search implicit video.
		
		if (is_array ( $matches ) && is_array ( $matches ['src'] )) {
			$res =  array();
			foreach ( $matches ['src'] as $src ) {
				$res [] = urldecode( str_replace('\u0026amp','',$src) );
			}
    	return $res;
		}

		return false;

	}

  protected function getCode(){
    return 'youtube';
  }
  
	protected function _getVideoSrc(){
		$pattern = '#([^\?]*)?v=([^\&]*)#im';
    
		preg_match ( $pattern, $this->_url, $matches ); // search implicit video.

		if(is_array($matches) && !empty($matches[0])){
			return 'http://www.youtube.com/v/'.$matches[2];
		}
	}
}

class Wall_Parse_Metacafe extends Wall_Parse_News{

  protected function isInternal(){
    return 1;
  }

  protected function getCode(){
    return 'metacafe';
  }

	protected function _getVideoSrc(){
		$pattern = '#www.metacafe.com/watch/(?P<id>\d+)/(?P<name>\w+)/#im';
		preg_match ( $pattern, $this->_url, $matches ); // search implicit video.

		if(is_array($matches) && !empty($matches[0])){
			return 'http://www.metacafe.com/fplayer/'.$matches['id'].'/'.$matches['name'].'.flv';
		}
	}

  
}

class Wall_Parse_Vimeo extends Wall_Parse_News{

  protected function isInternal(){
    return 1;
  }

  protected function getCode(){
    return 'vimeo';
  }

	protected function _getVideoSrc(){
		$pattern = '#www.vimeo.com/(?P<id>\d+)/#im';
		preg_match ( $pattern, $this->_url, $matches ); // search implicit video.

		if(is_array($matches) && !empty($matches[0])){
			return 'http://player.vimeo.com/video/'.$matches['id'];
		}
	}
}

class Wall_Parse_Break extends Wall_Parse_News{

  protected function isInternal(){
    return 1;
  }

  protected function getCode(){
    return 'break';
  }

	protected function _getVideoSrc(){
     
		$pattern = '#www.break.com/(?P<id>\d+)/#im';
		preg_match ( $pattern, $this->_url, $matches ); // search implicit video.

		if(is_array($matches) && !empty($matches[0])){
			return 'http://embed.break.com/'.$matches['id'];
		}
	}
}

class Wall_Parse
{
    public static function factory($url){
    $url = trim($url);
    if(strpos($url,'://')==false){
      $url =  'http://'. $url;
    }
    
		$class = 'Wall_Parse_'.ucfirst(self::checkUrl($url));
		return new $class($url);		
	}
	public static function checkUrl($url){

		$parts = parse_url($url);
		$host = @$parts['host'];
		if($host)
                {
                    $host =  strtolower($host);
		}
		switch($host){
			case 'www.youtube.com':
				return 'youtube';
                        case 'vimeo.com':case 'www.vimeo.com':
                            return 'vimeo';
                        case 'www.break.com':
                            $str=trim($url, '/');
                            $arr = explode('-',$str);
                            $id_url=$arr[count($arr)-1];
                            if(is_numeric($id_url))
                            {
                                return 'break';
                            }
                            else
                            {
                                return 'news';
                            }
                        case 'www.metacafe.com';
                            return 'metacafe';
			default:
                            return 'news';
		}
	}    
}